//
//  CaptureLocationViewController.m
//  CarPark
//
//  Created by oceans on 2019/8/8.
//  Copyright © 2019 oceans. All rights reserved.
//

#import "CaptureLocationViewController.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import "CaptureInstallListViewController.h"
#import "CaptureInstallViewController.h"
#import "CenterCircle.h"

@interface CaptureLocationViewController () <MAMapViewDelegate, AMapGeoFenceManagerDelegate, CLLocationManagerDelegate>


@property (strong, nonatomic) MAMapView *mapView;
@property (strong, nonatomic) AMapGeoFenceManager *geoFenceManger;
@property (strong, nonatomic) CLLocationManager *locationManager;
@property (strong, nonatomic) UIButton *next;
@property (weak, nonatomic) CenterCircle *center;
@end

@implementation CaptureLocationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"地图定位";
    
    [self setupView];
    [self startLocation];
}

- (void)startLocation {
    
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    if (status == kCLAuthorizationStatusNotDetermined) {
        [self.locationManager requestWhenInUseAuthorization];
    }else if (status == kCLAuthorizationStatusDenied || status == kCLAuthorizationStatusRestricted) {
        UIAlertController * alertVC = [UIAlertController alertControllerWithTitle:@"允许\"定位\"提示" message:@"请在设置中打开定位" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * ok = [UIAlertAction actionWithTitle:@"打开定位" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //打开定位设置
            NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if (@available(iOS 10.0, *)) {
                [[UIApplication sharedApplication] openURL:settingsURL options:@{UIApplicationOpenURLOptionUniversalLinksOnly: @YES} completionHandler:nil];
            }else {
                [[UIApplication sharedApplication] openURL:settingsURL];
            }
        }];
        UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertVC addAction:cancel];
        [alertVC addAction:ok];
        [self presentViewController:alertVC animated:YES completion:nil];
    }
}

- (void)setupView {
    
    [AMapServices sharedServices].enableHTTPS = YES;
    
    MAUserLocationRepresentation *r = [[MAUserLocationRepresentation alloc] init];
    r.showsAccuracyRing = NO;
    self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0.0, XNavigationHeight, ScreenWidth, ScreenHeight-XNavigationHeight-XBotSafeSpace-40.0)];
    _mapView.zoomLevel = 13;
    _mapView.showsUserLocation = YES;
    _mapView.userTrackingMode = MAUserTrackingModeFollow;
    _mapView.delegate = self;
    [_mapView updateUserLocationRepresentation:r];
    [self.view addSubview:_mapView];
    
    self.geoFenceManger = [[AMapGeoFenceManager alloc] init];
    _geoFenceManger.delegate = self;
    _geoFenceManger.allowsBackgroundLocationUpdates = NO;
    _geoFenceManger.activeAction =
    AMapGeoFenceActiveActionInside | AMapGeoFenceActiveActionOutside |
    AMapGeoFenceActiveActionStayed;
    for (NSInteger i = 0; i < _captures.count; i ++) {
        
        NSDictionary *dic = _captures[i];
        [_geoFenceManger addCircleRegionForMonitoringWithCenter:CLLocationCoordinate2DMake([dic[@"lat"] floatValue], [dic[@"lng"] floatValue]) radius:[_info[@"fence_radius"] floatValue] customID:@"location"];
        
        MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];
        pointAnnotation.coordinate = CLLocationCoordinate2DMake([dic[@"lat"] floatValue], [dic[@"lng"] floatValue]);
        pointAnnotation.title = dic[@"name"];
        [_mapView addAnnotation:pointAnnotation];
    }
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.titleLabel.font = [UIFont systemFontOfSize:15.0];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button setTitle:@"下一步-安装设备" forState:UIControlStateNormal];
    button.frame = CGRectMake(0, ScreenHeight-XBotSafeSpace-40.0, ScreenWidth, 40.0+XBotSafeSpace);
    [button addTarget:self action:@selector(start) forControlEvents:UIControlEventTouchUpInside];
    button.backgroundColor = COLOR(242, 242, 242, 1);
    [self.view addSubview:button];
    self.next = button;
//    button.enabled = NO;
    self.next.backgroundColor = COLOR(101, 101, 101, 1);
    [self.next setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
}

- (void)start {
    
//    CaptureInstallListViewController *con = [[CaptureInstallListViewController alloc] init];
//    con.info = _info;
//    [self.navigationController pushViewController:con animated:YES];
    CaptureInstallViewController *con = [[CaptureInstallViewController alloc] init];
    con.info = _info;
    con.captures = _captures;
    [self.navigationController pushViewController:con animated:YES];
}

#pragma mark - cllocation delegate

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    if (status == kCLAuthorizationStatusNotDetermined) {
        
    }else if (status == kCLAuthorizationStatusDenied || status == kCLAuthorizationStatusRestricted) {
        
    }else {
        
        [self.locationManager startUpdatingLocation];
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    //    [self.locationManager stopUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    [self.locationManager stopUpdatingLocation];
}


#pragma mark - MAMapViewDelegate

- (void)mapView:(MAMapView *)mapView
didUpdateUserLocation:(MAUserLocation *)userLocation
updatingLocation:(BOOL)updatingLocation {
    
    NSArray *array = [_geoFenceManger geoFenceRegionsWithCustomID:@"self"];
    if (array && array.count) {
        [_geoFenceManger removeGeoFenceRegionsWithCustomID:@"self"];
    }
    if (_center) {
        [_mapView removeOverlay:_center];
        _center = nil;
    }
    [_geoFenceManger addCircleRegionForMonitoringWithCenter:userLocation.location.coordinate radius:[_info[@"fence_radius"] floatValue] customID:@"self"];
}

- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay {
    if ([overlay isKindOfClass:[MAPolygon class]]) {
        MAPolygonRenderer *polylineRenderer = [[MAPolygonRenderer alloc] initWithPolygon:overlay];
        polylineRenderer.lineWidth          = 3.0f;
        polylineRenderer.strokeColor        = [UIColor orangeColor];
        
        return polylineRenderer;
    } else if ([overlay isKindOfClass:[MACircle class]]) {
        MACircleRenderer *circleRenderer = [[MACircleRenderer alloc] initWithCircle:overlay];
        if ([overlay isKindOfClass:[CenterCircle class]]) {
            MACircleRenderer *ren = [[MACircleRenderer alloc] initWithCircle:overlay];
            ren.fillColor = [[UIColor redColor] colorWithAlphaComponent:0.3];
            ren.lineWidth         = 3.0f;
            ren.strokeColor =
            [UIColor colorWithRed:1 green:0 blue:0 alpha:1];
            //精度圈 填充颜色
            ren.fillColor =
            [UIColor colorWithRed:1 green:0 blue:0 alpha:0.1];
            
            return ren;
        }
        circleRenderer.lineWidth         = 3.0f;
        circleRenderer.strokeColor =
        [UIColor colorWithRed:33 / 255.0 green:196 / 255.0 blue:206 / 255.0 alpha:1];
        //精度圈 填充颜色
        circleRenderer.fillColor =
        [UIColor colorWithRed:33 / 255.0 green:196 / 255.0 blue:206 / 255.0 alpha:0.3];
        
        return circleRenderer;
    }
    return nil;
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation {
    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {
        static NSString *pointReuseIndetifier = @"pointReuseIndetifier";
        MAPinAnnotationView *annotationView   = (MAPinAnnotationView *)[mapView
                                                                        dequeueReusableAnnotationViewWithIdentifier:pointReuseIndetifier];
        if (annotationView == nil) {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation
                                                             reuseIdentifier:pointReuseIndetifier];
        }
        
        annotationView.canShowCallout = YES;
        annotationView.animatesDrop   = YES;
        annotationView.draggable      = NO;
        annotationView.rightCalloutAccessoryView =
        [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        
        return annotationView;
    }
    
    return nil;
}

#pragma mark - AMapGeoFenceManagerDelegate

// 如果需要后台定位权限时，需要实现
- (void)amapGeoFenceManager:(AMapGeoFenceManager *)manager
      doRequireLocationAuth:(CLLocationManager *)locationManager {
    [locationManager requestAlwaysAuthorization];
}

//添加地理围栏完成后的回调，成功与失败都会调用
- (void)amapGeoFenceManager:(AMapGeoFenceManager *)manager
didAddRegionForMonitoringFinished:(NSArray<AMapGeoFenceRegion *> *)regions
                   customID:(NSString *)customID
                      error:(NSError *)error {
    
    if (error) {
        NSLog(@"======= circle error %@", error);
    } else {
        AMapGeoFenceCircleRegion *circleRegion =
        (AMapGeoFenceCircleRegion *)regions.firstObject; //一次添加一个圆形围栏，只会返回一个
        if ([circleRegion.customID isEqualToString:@"self"]) {
            if (_center) {
                [_mapView removeOverlay:_center];
                _center = nil;
            }
            CenterCircle *circleOverlay = [CenterCircle circleWithCenterCoordinate:circleRegion.center radius:circleRegion.radius];
            [self.mapView addOverlay:circleOverlay];
            _center = circleOverlay;
        }else {
            MACircle *circleOverlay =
            [self showCircleInMap:circleRegion.center radius:circleRegion.radius];
        }
        //        [self.mapView setVisibleMapRect:circleOverlay.boundingMapRect
        //                            edgePadding:UIEdgeInsetsMake(20, 20, 20, 20)
        //                               animated:YES]; //设置地图的可见范围，让地图缩放和平移到合适的位置
    }
}

//地理围栏状态改变时回调，当围栏状态的值发生改变，定位失败都会调用
- (void)amapGeoFenceManager:(AMapGeoFenceManager *)manager
didGeoFencesStatusChangedForRegion:(AMapGeoFenceRegion *)region
                   customID:(NSString *)customID
                      error:(NSError *)error {
    if (error) {
        NSLog(@"status changed error %@", error);
    } else {
        NSLog(@"status changed %@", [region description]);
        
        NSString *status = @"unknown";
        switch (region.fenceStatus) {
            case AMapGeoFenceRegionStatusInside:
                status = @"Inside";
                //                [self checkNext];
                
                break;
            case AMapGeoFenceRegionStatusOutside:
                status = @"Outside";
                
                break;
            case AMapGeoFenceRegionStatusStayed:
                status = @"Stayed";
                break;
                
            default:
                break;
        }
    }
}

- (void)showInMapWithRegion:(AMapGeoFenceRegion *)region {
    if (region == nil) { return; }
    
    AMapGeoFenceCircleRegion *circleRegion = (AMapGeoFenceCircleRegion *)region;
    MACircle *circleOverlay = [self showCircleInMap:circleRegion.center radius:circleRegion.radius];
    [self.mapView setVisibleMapRect:circleOverlay.boundingMapRect
                        edgePadding:UIEdgeInsetsMake(20, 20, 20, 20)
                           animated:YES]; //设置地图的可见范围，让地图缩放和平移到合适的位置
}

//添加地理围栏对应的Overlay，方便查看。地图上显示圆
- (MACircle *)showCircleInMap:(CLLocationCoordinate2D)coordinate radius:(NSInteger)radius {
    MACircle *circleOverlay = [MACircle circleWithCenterCoordinate:coordinate radius:radius];
    [self.mapView addOverlay:circleOverlay];
    return circleOverlay;
}

@end
